package org.linlinjava.litemall.admin.controller;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.*;
import static org.linlinjava.litemall.core.payment.PaymentResponseCode.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.linlinjava.litemall.admin.beans.annotation.LogAnno;
import org.linlinjava.litemall.admin.beans.annotation.LoginAdminId;
import org.linlinjava.litemall.admin.config.AdminAccountToken;
import org.linlinjava.litemall.admin.config.AdminMobOremailToken;
import org.linlinjava.litemall.admin.service.CaptchaCodeManager;
import org.linlinjava.litemall.admin.service.LogHelper;
import org.linlinjava.litemall.admin.service.ShopService;
import org.linlinjava.litemall.admin.util.Permission;
import org.linlinjava.litemall.admin.util.PermissionUtil;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.util.*;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.dao.LitemallAdminMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员身份验证控制器
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Api(tags = "管理员身份验证API")
@RestController
@RequestMapping("/admin/auth")
@Validated
public class AdminAuthController {

    /**
     * 管理服务
     */
    @Autowired
    private LitemallAdminService adminService;

    @Autowired
    private LitemallAdminMapper litemallAdminMapper;

    /**
     * 角色服务
     */
    @Autowired
    private LitemallRoleService roleService;
    /**
     * 许可服务
     */
    @Autowired
    private LitemallPermissionService permissionService;
    /**
     * litemall店服务
     */
    @Autowired
    private LitemallShopService litemallShopService;
    /**
     * 日志助手
     */
    @Autowired
    private LogHelper logHelper;
    /**
     * 店服务
     */
    @Autowired
    private ShopService shopService;

    @Autowired
    private LitemallTokenService litemallTokenService;

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private NotifyService notifyService;

    /**
     * 登录
     *
     * @param body    身体
     * @param request 请求
     * @return {@link Object}
     *//*
     *  { username : value, password : value }
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    @LogAnno
    public Object login(@RequestBody String body, HttpServletRequest request) {
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResponseUtil.badArgument();
        }

        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(new UsernamePasswordToken(username, password));
        } catch (UnknownAccountException uae) {
            logHelper.logAuthFail("登录", "用户帐号或密码不正确");
            return ResponseUtil.fail(ADMIN_INCORRECT_ACCOUNT, "用户帐号或密码不正确");
        } catch (LockedAccountException lae) {
            logHelper.logAuthFail("登录", "用户帐号已锁定不可用");
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号已锁定不可用");

        } catch (AuthenticationException ae) {
            logHelper.logAuthFail("登录", "认证失败");
            return ResponseUtil.fail(ADMIN_AUTHENTICATION_FAILURE_ACCOUNT, "认证失败");
        }

        currentUser = SecurityUtils.getSubject();
        currentUser.getSession().setTimeout(4*60*60*1000);
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
        admin.setLastLoginIp(IpUtil.getIpAddr(request));
        admin.setLastLoginTime(LocalDateTime.now());
        adminService.updateById(admin);

        logHelper.logAuthSucceed("登录");

        // userInfo
        Map<String, Object> adminInfo = new HashMap();
        adminInfo.put("nickName", admin.getUsername());
        adminInfo.put("avatar", admin.getAvatar());
        Map<Object, Object> result = new HashMap();
        Serializable token = currentUser.getSession().getId();
        result.put("token", token);
        result.put("adminInfo", adminInfo);

        //删除用户之前令牌
        /*List<LitemallToken> litemallTokens = litemallTokenService.list(Wrappers.lambdaQuery(LitemallToken.class)
                .eq(LitemallToken::getUserId, admin.getId()));

        litemallTokenService.removeBatchByIds(litemallTokens);*/

        //重新设置令牌
        LitemallToken litemallToken = LitemallToken.builder()
                .userId(admin.getId()).serve(3)
                .username(username)
                .password(password)
                .device(3).validDays(4)
                .token(token.toString()).valid(0)
                .loginTime(LocalDateTime.now())
                .build();
        litemallTokenService.save(litemallToken);
        //存储token
        /*LitemallToken litemallToken = LitemallToken.builder()
                .userId(admin.getId()).serve(3)
                .device(3).validDays(4)
                .token(token.toString()).valid(0)
                .loginTime(LocalDateTime.now())
                .build();
        //device还不确定具体登陆设备

        List<LitemallToken> litemallTokens = litemallTokenService.list(Wrappers.lambdaQuery(LitemallToken.class)
                .eq(LitemallToken::getUserId, admin.getId())
                .eq(LitemallToken::getValid, 0));
        if(litemallTokens.size()>0){
            litemallTokens.stream().forEach(litemallToken1 -> litemallToken1.setValid(1));
            //有另一端登陆 「踢人下线」
            litemallTokenService.updateBatchById(litemallTokens);
        }

        litemallTokenService.save(litemallToken);*/

        return ResponseUtil.ok(result);
    }


    /**
     * 手机邮箱号登陆
     */
    @ApiOperation("手机邮箱号登陆")
    @LogAnno
    @PostMapping("mobOremailLogin")
    public ResponseUtil.Response mobOremailLogin(@RequestBody String body, HttpServletRequest request){
        String mobOremail = JacksonUtil.parseString(body, "mobOremail");
        String authCode = JacksonUtil.parseString(body, "code").replace(" ", "");
        LitemallAdmin litemallAdmin = litemallAdminMapper.selectOne(Wrappers.lambdaQuery(LitemallAdmin.class)
                .eq(LitemallAdmin::getMobile, mobOremail)
                .eq(LitemallAdmin::getDeleted, 0)
                .or()
                .eq(LitemallAdmin::getEmail, mobOremail)
                .eq(LitemallAdmin::getDeleted, 0)
        );
        if(ObjectUtil.isNull(litemallAdmin)){
            return ResponseUtil.fail(738,"账号不存在");
        }
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.login(new UsernamePasswordToken(mobOremail,authCode));
        currentUser = SecurityUtils.getSubject();
        currentUser.getSession().setTimeout(4*60*60*1000);
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
        admin.setLastLoginIp(IpUtil.getIpAddr(request));
        admin.setLastLoginTime(LocalDateTime.now());
        adminService.updateById(admin);

        logHelper.logAuthSucceed("登录");

        // userInfo
        Map<String, Object> adminInfo = new HashMap<String, Object>();
        adminInfo.put("nickName", admin.getUsername());
        adminInfo.put("avatar", admin.getAvatar());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", currentUser.getSession().getId());
        result.put("adminInfo", adminInfo);
        return ResponseUtil.ok(result);
    }

    /**
     * 注销
     *
     * @return {@link Object}
     *//*
     *
     */
    @ApiOperation(value = "注销")
    @RequiresAuthentication
    @PostMapping("/logout")
    @LogAnno
    public Object logout(@LoginAdminId Integer adminId) {
        Subject currentUser = SecurityUtils.getSubject();
        LitemallToken litemallToken = litemallTokenService.getOne(Wrappers.lambdaQuery(LitemallToken.class)
                .eq(LitemallToken::getUserId,adminId)
                .eq(LitemallToken::getServe, 2)
                .eq(LitemallToken::getValid, 0));
        if(ObjectUtil.isNull(litemallToken)){
            return ResponseUtil.ok();
        }
        //清除令牌
        litemallTokenService.removeById(litemallToken);
        logHelper.logAuthSucceed("退出");
        currentUser.logout();
        return ResponseUtil.ok();
    }


    /**
     * 未登录
     * 501
     *
     * @return {@link ResponseUtil.Response}
     */
    @ApiOperation(value = "501")
    @GetMapping("notLogin")
    public ResponseUtil.Response norLogin(){
        return ResponseUtil.unlogin();
    }

    /**
     * 信息
     *
     * @return {@link Object}
     */
    @ApiOperation(value = "信息")
    @RequiresAuthentication
    @GetMapping("/info")
    @LogAnno
    public Object info() {
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();

        Map<String, Object> data = new HashMap<>();
        data.put("id", admin.getId());
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());

        LitemallShop shop = litemallShopService.findById(admin.getShopId());
        data.put("shop", shop);
        if(null != shop) {
        	List<LitemallRegion> shopRegions = shopService.queryShopRegions(shop.getId());
        	data.put("shopRegions", shopRegions);
        }

        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.queryByIds(roleIds);
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);
        data.put("roles", roles);
        // NOTE
        // 这里需要转换perms结构，因为对于前端而已API形式的权限更容易理解
        data.put("perms", toApi(permissions));
        return ResponseUtil.ok(data);
    }

    /**
     * 上下文
     */
    @Autowired
    private ApplicationContext context;
    /**
     * 系统权限映射
     */
    private HashMap<String, String> systemPermissionsMap = null;

    /**
     * 对api
     *
     * @param permissions 权限
     * @return {@link Collection}<{@link String}>
     */
    private Collection<String> toApi(Set<String> permissions) {
        if (systemPermissionsMap == null) {
            systemPermissionsMap = new HashMap<>();
            final String basicPackage = "org.linlinjava.litemall.admin";
            List<Permission> systemPermissions = PermissionUtil.listPermission(context, basicPackage);
            for (Permission permission : systemPermissions) {
                String perm = permission.getRequiresPermissions().value()[0];
                String api = permission.getApi();
                systemPermissionsMap.put(perm, api);
            }
        }

        Collection<String> apis = new HashSet<>();
        for (String perm : permissions) {
            String api = systemPermissionsMap.get(perm);
            apis.add(api);

            if (perm.equals("*")) {
                apis.clear();
                apis.add("*");
                return apis;
                //                return systemPermissionsMap.values();

            }
        }
        return apis;
    }

    /**
     * page401
     *
     * @return {@link Object}
     */
    @GetMapping("/401")
    public Object page401() {
        return ResponseUtil.unlogin();
    }

    /**
     * 页面索引
     *
     * @return {@link Object}
     */
    @GetMapping("/index")
    public Object pageIndex() {
        return ResponseUtil.ok();
    }

    /**
     * page403
     *
     * @return {@link Object}
     */
    @GetMapping("/403")
    public Object page403() {
        return ResponseUtil.unauthz();
    }



    /**
     * 验证码
     * 请求验证码
     * <p>
     * TODO
     * 这里需要一定机制防止短信验证码被滥用
     *
     * @param body 手机号码 { mobile: xxx, type: xxx }
     * @return {@link Object}
     */
    @PostMapping("captcha")
    @LogAnno
    public Object captcha( @RequestBody String body) {
        String type = null;
        //取出username
        String userName = JacksonUtil.parseString(body,"mobOremail");
        //取出status
        Integer status = JacksonUtil.parseInteger(body, "status");

        LitemallAdmin litemallAdmin = litemallAdminMapper.selectOne(Wrappers.lambdaQuery(LitemallAdmin.class)
                .eq(LitemallAdmin::getMobile, userName)
                .eq(LitemallAdmin::getDeleted, 0)
                .or()
                .eq(LitemallAdmin::getEmail, userName)
                .eq(LitemallAdmin::getDeleted, 0)
        );

        if(ObjectUtil.isNull(litemallAdmin)){
            return ResponseUtil.fail(738,"账号不存在");
        }
        type= RegexUtil.isEmailExact(userName)?"email":"mobile";


        if ("email".equals(type)) {

            if (!notifyService.isMailEnable()) {
                return ResponseUtil.fail(AUTH_CAPTCHA_UNSUPPORT, "邮件发送后台验证码服务不支持");
            }
            String code = CharUtil.getRandomNum(6);
            notifyService.notifySmsTemplate(MOBILE_CODE_ONE+litemallAdmin.getMobile(), NotifyType.CAPTCHA, new String[]{code});

            boolean successful = CaptchaCodeManager.addToCache(litemallAdmin.getEmail()+status, code);
            if (!successful) {
                return ResponseUtil.fail(AUTH_CAPTCHA_FREQUENCY, "验证码未超时10分钟，不能发送");
            }
            notifyService.notifyMailTemplate("Lumiere Cafe Account Verification", NotifyType.CAPTCHA, litemallAdmin.getEmail(), new String[]{code});
        } else {
            if (!notifyService.isSmsEnable()) {
                return ResponseUtil.fail(AUTH_CAPTCHA_UNSUPPORT, "小程序后台验证码服务不支持");
            }
            String code = CharUtil.getRandomNum(6);
            // TODO
            // 根据type发送不同的验证码
            notifyService.notifySmsTemplate(MOBILE_CODE_ONE+litemallAdmin.getMobile(), NotifyType.CAPTCHA, new String[]{code});

            boolean successful = CaptchaCodeManager.addToCache(litemallAdmin.getMobile()+status, code);
            if (!successful) {
                return ResponseUtil.fail(AUTH_CAPTCHA_FREQUENCY, "验证码未超时10分钟，不能发送");
            }
        }
        return ResponseUtil.ok();
    }


}
